package handle

import (
	"comic-mgmt-sys/cache"
	"comic-mgmt-sys/model"
	"comic-mgmt-sys/pkg"
	"encoding/json"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不能为空",
		})
		return
	}
	redis_key := "user_login" + username
	errCache, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()
	if errCache >= 3 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误3次，禁止登录",
		})
		return
	}
	var user model.User
	err := model.DB.Where("username = ?", username).First(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查找失败",
		})
		return
	}
	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户名不存在",
		})
		return
	}
	if user.Password != pkg.Md5(password) {
		cache.Rdb.Incr(cache.Ctx, redis_key)

		if errCache == 2 {
			cache.Rdb.Set(cache.Ctx, redis_key, "1", time.Hour*2)
			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "错误3次，封禁账号",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登录成功",
		"data": user,
	})
	return
}
func Create(c *gin.Context) {
	title := c.PostForm("title")
	content := c.PostForm("content")
	comic := model.Comic{

		Title:   title,
		Content: content,
	}
	err := model.DB.Create(&comic).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}
func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "4"))
	offset := (page - 1) * size
	var comic []model.Comic
	redis_key := "user_list" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Offset(offset).Limit(size).Find(&comic)
		jsonData, _ := json.Marshal(comic)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &comic)
	}

	var total int64
	model.DB.Model(&model.Comic{}).Count(&total)
	c.JSON(200, gin.H{
		"code":  200,
		"data":  comic,
		"total": total,
	})
	return

}
func Detail(c *gin.Context) {
	id := c.Query("id")
	var comic model.Comic
	redis_key := "user_detail" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Where("id = ?", id).First(&comic)
		jsonData, _ := json.Marshal(comic)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &comic)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"data": comic,
	})
	return

}
func Del(c *gin.Context) {
	id := c.Query("id")
	var comic model.Comic
	err := model.DB.Where("id = ?", id).Delete(&comic).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 200,
			"msg":  "删除失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "删除成功",
	})
	return
}
func UserOrderList(c *gin.Context) {
	uid, _ := strconv.Atoi(c.Query("uid"))
	//SELECT
	//  *
	//FROM
	//  roles LEFT JOIN user_roles ON user_roles.rid=roles.id
	//  WHERE user_roles.uid = 1
	var role model.Role
	redis_key := "order_list" + strconv.Itoa(uid)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Table("role").
			Joins("roles LEFT JOIN user_roles ON user_roles.rid=roles.id").
			Where("user_roles.uid = 1", uid).Find(&role)
		jsonData, _ := json.Marshal(role)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &role)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"data": role,
	})
}
func UserOrderDetail(c *gin.Context) {
	id := c.Query("id")
	//SELECT
	//  *
	//FROM
	//  roles LEFT JOIN user_roles ON user_roles.rid=roles.id
	//  WHERE user_roles.uid = 1
	var role model.Role
	redis_key := "order_Detail" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Table("role").
			Joins("roles LEFT JOIN user_roles ON user_roles.rid=roles.id").
			Where("user_roles.uid = 1", id).Find(&role)
		jsonData, _ := json.Marshal(role)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &role)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"data": role,
	})

}
func CarOrderList(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "4"))
	offset := (page - 1) * size
	var car []model.CarOrderList
	//SELECT
	//car_orders.id AS Id,
	//  car_orders.order_code AS OrderCode,
	//  car_orders.order_form AS OrderForm,
	//  cars.car_name AS CarName,
	//  cars.car_price AS CarPrice,
	//  cars.car_num AS CarNum,
	//  car_orders.order_time as OrderTime
	//FROM
	//  car_orders
	//  LEFT JOIN cars ON cars.id = car_orders.cid
	redis_key := "car_list" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Table("car_orders").
			Select(
				"car_orders.id AS Id",
				"car_orders.order_code AS OrderCode",
				"car_orders.order_form AS OrderForm",
				"cars.car_name AS CarName",
				"cars.car_price AS CarPrice",
				"cars.car_num AS CarNum",
				"car_orders.order_time as OrderTime",
			).Joins("LEFT JOIN cars ON cars.id = car_orders.cid").
			Offset(offset).Limit(size).Debug().Order("car_orders.id desc").Find(&car)
		jsonData, _ := json.Marshal(&car)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &car)
	}

	var total int64
	model.DB.Model(&model.CarOrder{}).Count(&total)
	c.JSON(200, gin.H{
		"code":  200,
		"data":  car,
		"total": total,
	})
	return
}
func CarOrderDetail(c *gin.Context) {
	id := c.Query("id")
	var car model.CarOrder
	redis_key := "car_detial" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Where("car_orders.id = ?", id).Find(&car)
		jsonData, _ := json.Marshal(&car)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &car)
	}
	c.JSON(200, gin.H{
		"code": 200,

		"data": car,
	})
	return

}
